package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.SalesTask;
import com.example.crm.entity.SalesTeam;
import com.example.crm.entity.User;
import com.example.crm.mapper.SalesTaskMapper;
import com.example.crm.mapper.SalesTeamMapper;
import com.example.crm.mapper.UserMapper;
import com.example.crm.service.SalesTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售任务服务实现类
 */
@Service
public class SalesTaskServiceImpl extends ServiceImpl<SalesTaskMapper, SalesTask> implements SalesTaskService {

    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private SalesTeamMapper salesTeamMapper;

    @Override
    public IPage<SalesTask> listTasksByPage(Map<String, Object> params) {
        // Create page object based on parameters
        Integer current = params.get("current") != null ? Integer.parseInt(params.get("current").toString()) : 1;
        Integer size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 10;
        Page<SalesTask> page = new Page<>(current, size);
        
        // Query tasks with custom mapper method
        IPage<SalesTask> taskPage = baseMapper.selectTasksByPage(page, params);
        
        // Populate related user information for each task
        taskPage.getRecords().forEach(this::populateUserInfo);
        
        return taskPage;
    }

    @Override
    public SalesTask getTaskDetail(Long id) {
        SalesTask task = getById(id);
        if (task != null) {
            populateUserInfo(task);
        }
        return task;
    }

    private void populateUserInfo(SalesTask task) {
        // Set owner information
        if (task.getOwnerId() != null) {
            User owner = userMapper.selectById(task.getOwnerId());
            if (owner != null) {
                task.setOwner(owner);
            }
        }
        
        // Set creator information
        if (task.getCreatorId() != null) {
            User creator = userMapper.selectById(task.getCreatorId());
            if (creator != null) {
                task.setCreator(creator);
            }
        }
        
        // Set team information
        if (task.getTeamId() != null) {
            SalesTeam team = salesTeamMapper.selectById(task.getTeamId());
            if (team != null) {
                task.setTeam(team);
            }
        }
        
        // Set priority text
        if (task.getPriority() != null) {
            switch (task.getPriority()) {
                case 1:
                    task.setPriorityText("高");
                    break;
                case 2:
                    task.setPriorityText("中");
                    break;
                case 3:
                    task.setPriorityText("低");
                    break;
                default:
                    task.setPriorityText("未知");
            }
        }
        
        // Set status text
        if (task.getStatus() != null) {
            switch (task.getStatus()) {
                case 0:
                    task.setStatusText("未开始");
                    break;
                case 1:
                    task.setStatusText("进行中");
                    break;
                case 2:
                    task.setStatusText("已完成");
                    break;
                case 3:
                    task.setStatusText("已取消");
                    break;
                default:
                    task.setStatusText("未知");
            }
        }
    }

    @Override
    public List<Map<String, Object>> getTaskStats(Long userId) {
        return baseMapper.countTasksByStatus(userId);
    }

    @Override
    public List<SalesTask> getTodayTasks(Long userId) {
        return baseMapper.selectTodayTasks(userId);
    }

    @Override
    public List<SalesTask> getRelatedTasks(Integer relatedType, Long relatedId) {
        LambdaQueryWrapper<SalesTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SalesTask::getRelatedType, relatedType)
                    .eq(SalesTask::getRelatedId, relatedId)
                    .orderByDesc(SalesTask::getCreateTime);
        
        List<SalesTask> tasks = list(queryWrapper);
        tasks.forEach(this::populateUserInfo);
        
        return tasks;
    }

    @Override
    public List<SalesTask> getTasksByTeamId(Long teamId) {
        LambdaQueryWrapper<SalesTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SalesTask::getTeamId, teamId)
                    .orderByDesc(SalesTask::getCreateTime);
        
        List<SalesTask> tasks = list(queryWrapper);
        tasks.forEach(this::populateUserInfo);
        
        return tasks;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTask(SalesTask task) {
        task.setCreateTime(LocalDateTime.now());
        task.setUpdateTime(LocalDateTime.now());
        
        if (task.getStatus() == null) {
            task.setStatus(0); // Default to "Not Started"
        }
        
        return save(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTask(SalesTask task) {
        task.setUpdateTime(LocalDateTime.now());
        
        // If task is marked as completed, set completion time
        if (task.getStatus() != null && task.getStatus() == 2 && task.getCompletionTime() == null) {
            task.setCompletionTime(LocalDateTime.now());
        }
        
        return updateById(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTaskStatus(Long id, Integer status) {
        SalesTask task = getById(id);
        if (task == null) {
            return false;
        }
        
        task.setStatus(status);
        task.setUpdateTime(LocalDateTime.now());
        
        // If task is marked as completed, set completion time
        if (status == 2) {
            task.setCompletionTime(LocalDateTime.now());
        }
        
        return updateById(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteTasks(List<Long> ids) {
        return removeByIds(ids);
    }
} 